import Realm from 'realm';
/**表定义区**/
// 资产
export const AssetTableName = 'Asset';
// 盘点
export const InventoryTableName = 'Inventory';
// 盘点详情
export const InventoryDetailTableName = 'InventoryDetail';
// 盘盈列表
export const InventoryMoreOutTableName = 'InventoryMoreOut';
// 数据中心机房
export const DatacenterRoomTableName = 'DatacenterRoom';
// 迁移原因
export const MoveReasonTableName = 'MoveReason';
// 位置迁移
export const MoveLocationTableName = 'MoveLocation';
// 位置迁移资产表
export const MoveLocationAssetTableName = 'MoveLocationAsset';
// 部门
export const DepartmentTableName = 'Department';
// 资产品牌
export const BrandTableName = 'Brand';
// 用户表
export const UserTableName = 'User';
// 配置
export const ConfigTableName = 'Config';
// 类型
export const TypeTableName = 'Type';
// 品牌型号
export const BrandModelTableName = 'BrandModel';



/**表结构定义区**/
const BrandModelSchema = {
    name: BrandModelTableName,
    primaryKey: 'value',
    properties: {
        value: 'string',
        label: 'string',
        isRoot: { type: 'bool', default: null, optional: true },
        isModel: { type: 'bool', default: null, optional: true },
        brandId: { type: 'string', default: null, optional: true },
        children: { type: 'list', objectType: BrandModelTableName },
    }
};

const TypeSchema = {
    name: TypeTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        name: 'string',
    }
};


const ConfigSchema = {
    name: ConfigTableName,
    primaryKey: 'id',
    properties: {
        id: 'string',
        name: 'string',
    }
};


const UserSchema = {
    name: UserTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        name: 'string',
        account: 'string',
        deptId_: { type: 'string', default: null, optional: true },
        deptName: { type: 'string', default: null, optional: true },
        email: { type: 'string', default: null, optional: true },
        oauthAccount: { type: 'string', default: null, optional: true },
        personId: { type: 'string', default: null, optional: true },
        personNo: { type: 'string', default: null, optional: true },
        phone: { type: 'string', default: null, optional: true },
        sex: { type: 'int', default: null, optional: true },
        status: { type: 'int', default: null, optional: true }
    }
};

const BrandSchema = {
    name: BrandTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        name: 'string',
    }
};

const DepartmentSchema = {
    name: DepartmentTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        name: 'string',
        isRoot: { type: 'bool', default: null, optional: true },
        pid_: { type: 'string', default: null, optional: true },
        root: { type: 'bool', default: null, optional: true },
        sort: { type: 'int', default: null, optional: true },
        depts: { type: 'list', objectType: DepartmentTableName },
    }
};

const MoveLocationSchema = {
    name: MoveLocationTableName,
    primaryKey: 'id',
    properties: {
        id: 'string',
        roomId: 'string',
        reasonId: 'string',
        assetIds: 'string',
    }
};


const MoveReasonSchema = {
    name: MoveReasonTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        name: 'string',
        showName: { type: 'string', default: null, optional: true },
    }
};


const DatacenterRoomSchema = {
    name: DatacenterRoomTableName,
    primaryKey: 'value',
    properties: {
        value: 'string',
        label: 'string',
        isRoot: { type: 'bool', default: null, optional: true },
        isRoom: { type: 'bool', default: null, optional: true },
        roomType: { type: 'int', default: null, optional: true },
        datacenterId: { type: 'string', default: null, optional: true },
        children: { type: 'list', objectType: DatacenterRoomTableName },
    }
};

const AssetSchema = {
    name: AssetTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        assetName: { type: 'string', default: null, optional: true },
        assetNo: { type: 'string', default: null, optional: true },
        brandId_: { type: 'string', default: null, optional: true },
        brandName: { type: 'string', default: null, optional: true },
        imgPath: { type: 'string', default: null, optional: true },
        modelId_: { type: 'string', default: null, optional: true },
        modelName: { type: 'string', default: null, optional: true },
        price: { type: 'int', default: null, optional: true },
        remark: { type: 'string', default: null, optional: true },
        rfidNo: { type: 'string', default: null, optional: true },
        roomId_: { type: 'string', default: null, optional: true },
        roomName: { type: 'string', default: null, optional: true },
        serialNo: { type: 'string', default: null, optional: true },
        status: { type: 'int', default: null, optional: true },
        statusName: { type: 'string', default: null, optional: true },
        status_: { type: 'string', default: null, optional: true },
        typeId_: { type: 'string', default: null, optional: true },
        typeName: { type: 'string', default: null, optional: true },
    }
};

const InventorySchema = {
    name: InventoryTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        createName: { type: 'string', default: null, optional: true },
        createTime: { type: 'string', default: null, optional: true },
        createTimeString: { type: 'string', default: null, optional: true },
        different: { type: 'int', default: null, optional: true },
        executeTime: { type: 'string', default: null, optional: true },
        inventoryCount: { type: 'int', default: null, optional: true },
        inventoryName: { type: 'string', default: null, optional: true },
        inventorySheetName: { type: 'string', default: null, optional: true },
        inventoryType: { type: 'int', default: null, optional: true },
        loss: { type: 'int', default: null, optional: true },
        noInventoryCount: { type: 'int', default: null, optional: true },
        normal: { type: 'int', default: null, optional: true },
        over: { type: 'int', default: null, optional: true },
        status: { type: 'int', default: null, optional: true },
        roomName: { type: 'string', default: null, optional: true },
        source: { type: 'int', default: null, optional: true },
        totalCount: { type: 'int', default: null, optional: true },
    }
};
const InventoryDetailSchema = {
    name: InventoryDetailTableName,
    primaryKey: 'id_',
    properties: {
        id_: 'string',
        inventoryId: { type: 'string', default: null, optional: true },
        assetId_: { type: 'string', default: null, optional: true },
        assetName: { type: 'string', default: null, optional: true },
        assetNo: { type: 'string', default: null, optional: true },
        brandName: { type: 'string', default: null, optional: true },
        modelName: { type: 'string', default: null, optional: true },
        rfidNo: { type: 'string', default: null, optional: true },
        roomName: { type: 'string', default: null, optional: true },
        serialNo: { type: 'string', default: null, optional: true },
        status: { type: 'int', default: null, optional: true },
        typeName: { type: 'string', default: null, optional: true },
    }
};

const InventoryMoreOutSchema = {
    name: InventoryMoreOutTableName,
    primaryKey: 'id',
    properties: {
        id: 'string',
        inventoryId: { type: 'string', default: null, optional: true },
        rfidNo: { type: 'string', default: null, optional: true },
    }
};


const instance = new Realm({
    schema: [
        AssetSchema, InventorySchema, DatacenterRoomSchema,
        MoveReasonSchema, MoveLocationSchema,
        DepartmentSchema, BrandSchema, UserSchema, ConfigSchema,
        TypeSchema, BrandModelSchema, InventoryDetailSchema,
        InventoryMoreOutSchema,],
    inMemory: false,
    deleteRealmIfMigrationNeeded: true,
});

/**方法定义区**/

// 插入品牌型号树
export function insertBrandModelTree(treeData) {
    return new Promise((resolve, reject) => {
        try {
            treeData.forEach((nodeData) => {
                createBrandModelNode(nodeData);
            });
            resolve(true);
        } catch (e) {
            reject(e);
        }
    });
}

function createBrandModelNode(nodeData, parentObject) {
    const node = {
        value: nodeData.value,
        label: nodeData.label,
        isRoot: parentObject ? false : true,
        isModel: nodeData.isModel,
        brandId: nodeData.brandId,
        children: [],
    };
    instance.write(() => {
        if (parentObject) {
            parentObject.children.push(node);
            instance.create(BrandModelTableName, parentObject, true);
        } else {
            instance.create(BrandModelTableName, node);
        }
    });

    if (nodeData.children && nodeData.children.length > 0) {
        nodeData.children.forEach((childData) => {
            createBrandModelNode(childData, node);
        });
    }
}


// 插入部门树
export function insertDepartmentTree(treeData) {
    return new Promise((resolve, reject) => {
        try {
            // instance.write(() => {
            treeData.forEach((nodeData) => {
                createDepartmentNode(nodeData);
            });
            resolve(true);
            // });
        } catch (e) {
            reject(e);
        }
    });
}

// 创建部门树节点
function createDepartmentNode(nodeData, parentObject) {
    const node = {
        id_: nodeData.id_,
        name: nodeData.name,
        isRoot: parentObject ? false : true,
        pid_: nodeData.pid_,
        root: nodeData.root,
        sort: nodeData.sort,
        depts: [],
    };

    instance.write(() => {
        if (parentObject) {
            parentObject.depts.push(node);
            instance.create(DepartmentTableName, parentObject, true);
        } else {
            instance.create(DepartmentTableName, node);
        }
    });

    if (nodeData.depts && nodeData.depts.length > 0) {
        nodeData.depts.forEach((child) => {
            createDepartmentNode(child, node);
        });
    }
}

// 插入数据中心机房树
export function insertDataCenterRoomTree(treeData) {
    return new Promise((resolve, reject) => {
        try {
            // instance.write(() => {
            treeData.forEach((nodeData) => {
                createDataCenterRoomNode(nodeData);
            });
            resolve(true);
            // });
        } catch (e) {
            reject(e);
        }
    });
}

// 创建数据中心机房树节点
function createDataCenterRoomNode(nodeData, parentObject) {
    const node = {
        value: nodeData.value,
        label: nodeData.label,
        isRoom: nodeData.isRoom,
        isRoot: parentObject ? false : true,
        roomType: nodeData.roomType,
        datacenterId: nodeData.datacenterId,
        children: [],
    };
    instance.write(() => {
        if (parentObject) {
            parentObject.children.push(node);
            instance.create(DatacenterRoomTableName, parentObject, true);
        } else {
            instance.create(DatacenterRoomTableName, node);
        }
    });
    if (nodeData.children && nodeData.children.length > 0) {
        nodeData.children.forEach((child) => {
            createDataCenterRoomNode(child, node);
        });
    }
}
// 插入数据 传入表名和数据
export function insert(tableName, data) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                instance.create(tableName, data);
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
// 插入数据 传入表名和数据list
export function insertList(tableName, dataList) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                dataList.forEach(data => {
                    instance.create(tableName, data);
                });
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}


// 更新数据 传入表名和数据
export function update(tableName, data) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                instance.create(tableName, data, true);
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
// 更新数据 传入表名和数据list
export function updateList(tableName, dataList) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                dataList.forEach(data => {
                    instance.create(tableName, data, true);
                });
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
// 删除数据 传入表名和数据
export function deleteById(tableName, id) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                let data = instance.objectForPrimaryKey(tableName, id);
                instance.delete(data);
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
// 删除数据 传入表名和数据list
export function deleteAll(tableName) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                let dataList = instance.objects(tableName);
                instance.delete(dataList);
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
// 查询数据 传入表名
export function queryAll(tableName) {
    return new Promise((resolve, reject) => {
        try {
            let dataList = instance.objects(tableName);
            resolve(dataList ? JSON.parse(JSON.stringify(dataList)) : dataList);
        } catch (e) {
            reject(e);
        }
    });
}
// 查询数据 传入表名和id
export function queryById(tableName, id) {
    return new Promise((resolve, reject) => {
        try {
            let data = instance.objectForPrimaryKey(tableName, id);
            resolve(data ? JSON.parse(JSON.stringify(data)) : data);
        } catch (e) {
            reject(e);
        }
    });
}
// 查询数据 传入表名和条件
export function queryByCondition(tableName, fieldName, fieldValue) {
    return new Promise((resolve, reject) => {
        try {
            let dataList = instance.objects(tableName).filtered(`${fieldName} == $0`, fieldValue);
            resolve(dataList ? JSON.parse(JSON.stringify(dataList)) : dataList);
        } catch (e) {
            reject(e);
        }
    });
}
// 查询数据 多个条件
export function queryByConditions(tableName, conditions) {
    return new Promise((resolve, reject) => {
        try {
            let dataList = instance.objects(tableName).filtered(conditions);
            resolve(dataList ? JSON.parse(JSON.stringify(dataList)) : dataList);
        } catch (e) {
            reject(e);
        }
    });
}

// 查询数据 传入表名和条件 排序 
export function queryByConditionSort(tableName, condition, sort) {
    return new Promise((resolve, reject) => {
        try {
            let dataList = instance.objects(tableName).filtered(condition).sorted(sort);
            resolve(dataList ? JSON.parse(JSON.stringify(dataList)) : dataList);
        } catch (e) {
            reject(e);
        }
    });
}

export function queryPage(tableName, page, size) {
    return new Promise((resolve, reject) => {
        try {
            let totol = instance.objects(tableName).length;
            let dataList = instance.objects(tableName).slice(page * size, (page + 1) * size);
            resolve({ totol: totol, data: dataList });
        } catch (e) {
            reject(e);
        }
    });
}

export function queryInventoryPage(fieldName, fieldValue, page, size) {
    return new Promise((resolve, reject) => {
        try {
            let inventoryCount = instance.objects(InventoryTableName).filtered(`${fieldName} == $0`, 2).length;
            let noInventoryCount = instance.objects(InventoryTableName).filtered(`${fieldName} == $0`, 1).length;
            let totol = instance.objects(InventoryTableName).filtered(`${fieldName} == $0`, fieldValue).length;
            let pages = Math.ceil(totol / size);
            let dataList = instance.objects(InventoryTableName).filtered(`${fieldName} == $0`, fieldValue).slice((page - 1) * size, page * size);
            resolve({
                inventoryCount: inventoryCount,
                noInventoryCount: noInventoryCount,
                detailList: { totol: totol, pages: pages, records: dataList }
            });
        } catch (e) {
            reject(e);
        }
    });
}
export function updateInventoryMoreOut(inventoryId, moreOutList) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                console.log(inventoryId);
                let dataList = instance.objects(InventoryMoreOutTableName).filtered(`inventoryId == $0`, inventoryId);
                instance.delete(dataList);
                moreOutList.forEach(moreOut => {
                    instance.create(InventoryMoreOutTableName, moreOut);
                });
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}

export function updateInventoryDetailStatus(inventoryId, detailList) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                let dataList = instance.objects(InventoryDetailTableName).filtered(`inventoryId == $0`, inventoryId);
                // 将需要更新的列表属性赋值给数据库中的列表
                detailList.forEach(detail => {
                    let data = dataList.filtered(`id_ == $0`, detail.id);
                    if (data && data.length > 0) {
                        data[0].status = detail.status;
                        // 更新
                        instance.create(InventoryDetailTableName, data[0], true);
                    }
                });
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}
export function deleteInventoryMoreOutByInventoryId(inventoryId) {
    return new Promise((resolve, reject) => {
        try {
            instance.write(() => {
                let dataList = instance.objects(InventoryMoreOutTableName).filtered(`inventoryId == $0`, inventoryId);
                instance.delete(dataList);
                resolve(true);
            });
        } catch (e) {
            reject(e);
        }
    });
}

export function queryInventoryDetail(inventoryId) {
    return new Promise((resolve, reject) => {
        try {
            let dataList = instance.objects(InventoryTableName).filtered(`id_ == $0`, inventoryId);
            if (dataList && dataList.length > 0) {
                let inventory = dataList[0];
                let detailList = instance.objects(InventoryDetailTableName).filtered(`inventoryId == $0`, inventoryId);
                inventory.detailList = detailList;
                let moreOutList = instance.objects(InventoryMoreOutTableName).filtered(`inventoryId == $0`, inventoryId);
                inventory.moreOutList = moreOutList;
                resolve(inventory);
            }
            resolve(null);
        } catch (e) {
            reject(e);
        }
    });
}

export function queryPageByCondition(tableName, fieldName, fieldValue, page, size) {
    return new Promise((resolve, reject) => {
        try {
            let totol = instance.objects(tableName).filtered(`${fieldName} == $0`, fieldValue).length;
            let pages = Math.ceil(totol / size);
            let dataList = instance.objects(tableName).filtered(`${fieldName} == $0`, fieldValue).slice(page * size, (page + 1) * size);
            resolve({ totol: totol, pages: pages, data: dataList });
        } catch (e) {
            reject(e);
        }
    });
}
export function queryPageByConditionSort(tableName, condition, sort, page, size) {
    return new Promise((resolve, reject) => {
        try {
            let totol = instance.objects(tableName).filtered(condition).sorted(sort).length;
            let pages = Math.ceil(totol / size);
            let dataList = instance.objects(tableName).filtered(condition).sorted(sort).slice(page * size, (page + 1) * size);
            resolve({ totol: totol, pages: pages, data: dataList });
        } catch (e) {
            reject(e);
        }
    });
}
